import React, { useState, useRef, useEffect, useCallback } from 'react';
import { ProCard, ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { Button, Col, Form, Modal, Row, Space, Table, Tag, message, } from 'antd';
import type { Key } from 'antd/lib/table/interface';
import ExportJsonExcel from "js-export-excel";
import { connect } from 'umi';
import type { Dispatch } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
export type Props = {
    dispatch?: Dispatch;
    getDetialTableListData?: any;
    notificationId?: any;
};
const statusMap = [
    {
        color: 'green',
        text: '已读',
    },
    {
        color: 'red',
        text: '未读',
    },
];
const roles = ['辅导员', '班导师', '班长', '团支书'];
const classes = ['电气2301', '电气2302', '电气2303', '电气2304'];
const time = ['2023/9/9', '2023/8/20', '2023/8/10']
const travel = ['自驾', '飞机', '火车', '其他']
const place = ['河北工业大学北辰校区', '滨海国际机场', '天津西站']
const is = ['是', '否']
const notifications = [
    '学习计划会议将于明天召开，请准时参加。',
    '本周体育活动推迟至下周，请做好准备。',
    '学校开展环境保护志愿者招募，请有兴趣的同学报名。',
    '各班班长请于本周五参加班长会议。',
    '团委组织乡村义务劳动活动，报名截止本周五。',
    '辅导员将于明天下午在办公室接待同学。',
];
//定义通知标题样式
const titleStyle = {
    fontWeight: 'bolder',
    fontSize: '20px',
    color: 'black',
};
//定义通知内容样式
const contentStyle = {
    whiteSpace: 'pre-wrap',
    textAlign: 'left',
    fontSize: '16px',
    lineHeight: '1.5',
};
export type Status = {
    color: string;
    text: string;
};
export type TableListItem = {
    key: number;
    stuName: string;
    callNumber: string;
    status: Status;
    isRead: string;
    stuCode: string;
    phoneNumber: string;
    majorLabel: string;
    classLabel: string;
    travel: string;
    departurePlace: string;
    departureTime: string;
    pickup: string;
    destination: string;
    arrivalTime: string;
    paidTuition: string;
    unpaidReason: string;
};
//制造假数据
const tableListDataSource: TableListItem[] = [];
for (let i = 0; i < 50; i += 1) {
    tableListDataSource.push({
        key: i,
        stuName: roles[Math.floor(Math.random() * roles.length)],
        stuCode: Math.floor(Math.random() * 1000).toString(),
        callNumber: notifications[Math.floor(Math.random() * notifications.length)],
        status: statusMap[Math.floor(Math.random() * 10) % 2],
        isRead: "",
        phoneNumber: Math.floor(Math.random() * 1000000).toString(),
        majorLabel: "电气",
        classLabel: classes[Math.floor(Math.random() * roles.length)],
        travel: travel[Math.floor(Math.random() * roles.length)],
        departurePlace: place[Math.floor(Math.random() * roles.length)],
        departureTime: time[Math.floor(Math.random() * roles.length)],
        pickup: is[Math.floor(Math.random() * roles.length)],
        destination: place[Math.floor(Math.random() * roles.length)],
        arrivalTime: time[Math.floor(Math.random() * roles.length)],
        paidTuition: is[Math.floor(Math.random() * roles.length)],
        unpaidReason: '无',
    });
    tableListDataSource.forEach(item => {
        item.isRead = item.status.text
    })
}
const columns: ProColumns<TableListItem>[] = [
    {
        title: '序号',
        align: 'center',
        width: 120,
        dataIndex: 'key',
    },
    {
        title: '姓名',
        width: 120,
        align: 'center',
        dataIndex: 'stuName',
    },
    {
        title: '学号',
        width: 120,
        align: 'center',
        dataIndex: 'stuCode',
    },
    {
        title: '专业',
        width: 120,
        align: 'center',
        dataIndex: 'majorLabel',
    },
    {
        title: '班级',
        width: 120,
        align: 'center',
        dataIndex: 'classLabel',
    },
    {
        title: '状态',
        width: 120,
        dataIndex: 'status',
        render: (_, record) => <Tag color={record.status?.color}>{record.status?.text}</Tag>,
        // 1. 添加filters属性用于配置筛选选项
        filters: [
            { text: '已读', value: '已读' },
            { text: '未读', value: '未读' },
        ],
        filterMultiple: false,
        // 2. 添加onFilter属性用于指定筛选处理函数
        onFilter: (value, record) => record.status?.text === value
    },
    {
        title: '联系方式',
        width: 120,
        align: 'center',
        dataIndex: 'phoneNumber',
    },
    {
        title: '出行交通类型',
        width: 120,
        align: 'center',
        dataIndex: 'travel',
    },
    {
        title: '出发地点',
        width: 120,
        align: 'center',
        dataIndex: 'departurePlace',
    },
    {
        title: '出发时间',
        width: 120,
        align: 'center',
        dataIndex: 'departureTime',
    },
    {
        title: '到达地点',
        width: 120,
        align: 'center',
        dataIndex: 'destination',
    },
    {
        title: '到达时间',
        width: 120,
        align: 'center',
        dataIndex: 'arrivalTime',
    },
    {
        title: '是否需要接站',
        width: 120,
        align: 'center',
        dataIndex: 'pickup',
        filters: [
            { text: '是', value: '是' },
            { text: '否', value: '否' },
        ],
        onFilter: (value, record) => record.pickup === value
    },
    {
        title: '是否已缴学费',
        width: 120,
        align: 'center',
        dataIndex: 'paidTuition',
        filters: [
            { text: '是', value: '是' },
            { text: '否', value: '否' },
        ],
        onFilter: (value, record) => record.paidTuition === value
    },
    {
        title: '未缴学费原因',
        width: 120,
        align: 'center',
        dataIndex: 'unpaidReason',
    },
];
const registerandPayDetail: React.FC = (props: any) => {
    // 使用useState钩子创建表格数据源的状态变量tableListData
    const [filteredInfo, setFilteredInfo] = useState({ status: "", pickup: "", paidTuition: "" });
    // 使用useState钩子创建状态变量，用于存储用户选择的行的keys
    const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
    const tableListNewData: TableListItem[] = [];
    const settableData = (pagination, filters, sorter) => {
        console.log(filters)
        setFilteredInfo(filters);
    }
    //下载列表（包括筛选）
    const downloadData = (value: TableListItem[]) => {
        tableListNewData.splice(0, tableListNewData.length)
        console.log(filteredInfo)
        value.forEach(item => {
            console.log(item)
            if (filteredInfo.status == null || filteredInfo.status == "") {
                if (filteredInfo.pickup == null || filteredInfo.pickup == "") {
                    if (filteredInfo.paidTuition == null || filteredInfo.paidTuition == "") {
                        tableListNewData.push(item)
                    } else if (filteredInfo.paidTuition.includes(item.paidTuition)) {
                        tableListNewData.push(item)
                    }
                } else if (filteredInfo.pickup.includes(item.pickup)) {
                    if (filteredInfo.paidTuition == null || filteredInfo.paidTuition == "") {
                        tableListNewData.push(item)
                    } else if (filteredInfo.paidTuition.includes(item.paidTuition)) {
                        tableListNewData.push(item)
                    }
                }
            } else if (filteredInfo.status.includes(item.isRead)) {
                if (filteredInfo.pickup == null || filteredInfo.pickup == "") {
                    if (filteredInfo.paidTuition == null || filteredInfo.paidTuition == "") {
                        tableListNewData.push(item)
                    } else if (filteredInfo.paidTuition.includes(item.paidTuition)) {
                        tableListNewData.push(item)
                    }
                } else if (filteredInfo.pickup.includes(item.pickup)) {
                    if (filteredInfo.paidTuition == null || filteredInfo.paidTuition == "") {
                        tableListNewData.push(item)
                    } else if (filteredInfo.paidTuition.includes(item.paidTuition)) {
                        tableListNewData.push(item)
                    }
                }
            }
        })
        handleExportCurrentExcel(tableListNewData)
    }
    const handleExportCurrentExcel = (ExcelData: any) => { //ExcelData为后端返回的data数组
        let sheetFilter = ["key", "stuName", "stuCode", "majorLabel", "classLabel", "isRead", "phoneNumber", "travel", "departurePlace", "departureTime", "destination", "arrivalTime", "pickup", "paidTuition", "unpaidReason"];
        let option = {
            fileName: '',
            datas: {
            },
        };
        option.fileName = '新生报到和缴纳学费信息详情';
        option.datas = [
            {
                sheetData: ExcelData,
                sheetName: '新生报到和缴纳学费信息详情',
                sheetFilter: sheetFilter,
                sheetHeader: ['序号', '姓名', '学号', '专业', '班级', '状态', '联系方式', '出行交通类型', '出发地点', '出发时间', '到达地点', '到达时间', '是否需要接站', '是否已缴学费', '未缴学费原因'],
                columnWidths: [5, 5, 5, 5, 5, 5, 10, 5, 10, 10, 10, 10, 5, 5, 10]
            },
        ];
        var toExcel = new ExportJsonExcel(option); //new
        toExcel.saveExcel(); //保存
    }
    const [detialTableListData, setDetialTableListData] = useState<TableListItem[]>([]);
    const [notificationResult, setNotificationResult] = useState({})
    useEffect(() => {
        console.log(props.notificationId)
        props.dispatch({
            type: 'Model_Counsellor/getNoticeDetailEffects',
            payload: {
                id: '1688102157292683266',
                callback: (value: any) => {
                    console.log(value)
                    setNotificationResult(value);
                },
            },
        });
        props.dispatch({
            type: 'Model_Counsellor/getStudentRegisterEffects',
            payload: {
                id: '1688102157292683266',
                callback: (value: any) => {
                    console.log(value)
                    value?.forEach(item => {
                        if (item.isRead == statusMap[0].text) {
                            item.status = statusMap[0]
                        }
                        else { item.status = statusMap[1] }
                        if (item.isPickup == "1") item.pickup = "是"
                        else if (item.isPickup == "0") item.pickup = "否"
                        if (item.isPaidtuition == "1") item.paidTuition = "是"
                        else if (item.isPaidtuition == "0") item.paidTuition = "否"
                        if (item.travelType == "0") item.travel = "公共交通"
                        else if (item.travelType == "1") item.travel = "自驾"
                        if (item.destination == "0") item.destination = "天津站"
                        else if (item.destination == "1") item.destination = "天津西站"
                        else if (item.destination == "2") item.destination = "天津南站"
                        else if (item.destination == "3") item.destination = "滨海国际机场"
                        else if (item.destination == "4") item.destination = "其他"
                    })
                    setDetialTableListData(value)
                },
            },
        });
    }, [props.getDetialTableListData, props.notificationId]);
    return (
        <PageContainer>
            <div>
                <ProCard title={<span style={titleStyle}>{`主题：${notificationResult?.title} `}</span>} headerBordered>
                    <Row justify="center">
                        <Col span={20}>
                            <pre style={contentStyle} dangerouslySetInnerHTML={{ __html: notificationResult?.content }} />
                        </Col>
                    </Row>
                </ProCard>

                <ProCard title={<span style={titleStyle}>{"通知详情"}</span>}>
                    <Space size={'middle'}>
                        <Button type="primary" onClick={() => downloadData(detialTableListData)}>
                            下载列表
                        </Button>
                    </Space>
                    <ProTable<TableListItem>
                        columns={columns}
                        onChange={settableData}
                        //配置表格的行选择功能。
                        rowSelection={{
                            selectedRowKeys, // 设置用户选择的行
                            onChange: (keys) => { setSelectedRowKeys(keys) }, // 更新用户选择的行
                            selections: [
                                Table.SELECTION_ALL, //全选
                                Table.SELECTION_INVERT, //反选
                                Table.SELECTION_NONE, //全不选
                            ],
                        }}
                        dataSource={detialTableListData}
                        options={{ reload: true }}
                        search={false}
                        pagination={{
                            //分页
                            pageSize: 10,
                        }}
                        rowKey="key"
                    />
                </ProCard>
            </div>
        </PageContainer>
    );
};

export default connect(({ Model_Counsellor }: any) => ({
    Model_Counsellor,

}))(registerandPayDetail);
